﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Resources;
using System.Web.Mvc;

namespace internal_website.Meta
{
    [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
    public sealed class LocalizedRegexAttribute : RegularExpressionAttribute, IClientValidatable
    {
        static LocalizedRegexAttribute()
        {
            // necessary to enable client side validation
            DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(LocalizedRegexAttribute), typeof(RegularExpressionAttributeAdapter));
        }
        public LocalizedRegexAttribute(string regularExpressionPattern, string errorMessage)
            : base(regularExpressionPattern)
        {
            ErrorMessage = errorMessage;
        }

        public LocalizedRegexAttribute(string regularExpressionPatternKeyName, string errorMessageResourceName, Type errorMessageResourceType)
            : base(LoadRegex(regularExpressionPatternKeyName, errorMessageResourceType))
        {
            ErrorMessageResourceType = errorMessageResourceType;
            ErrorMessageResourceName = errorMessageResourceName;
        }

        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            yield return new ModelClientValidationRule()
            {
                ValidationType = "localized-regex",
                ErrorMessage = ErrorMessage
            };
        }

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            if (value != null)
            {
                if (!base.IsValid(value))
                {
                    return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
                }
            }

            return ValidationResult.Success;
        }

        /// <summary>
        /// Returs a regular expression pattern string.
        /// </summary>
        /// <param name="key">Name of key in resource (file)</param>
        /// <param name="errorMessageResourceType"></param>
        private static string LoadRegex(string key, Type errorMessageResourceType)
        {
            var resourceManager = new ResourceManager(errorMessageResourceType);
            return resourceManager.GetString(key);
        }

    }
}